﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using Ext.Net;


namespace KamLib.Controls
{

    public static class UilViewPartHelper
    {
        /// <summary>
        /// Ищет в parents control-а ближайший IUilView, и регистрируется в нём.
        /// </summary>
        /// <param name="control"></param>
        public static void RegisterAsPart(Control control)
        {
            var part = control as IUilViewPart;
            if (part == null || part.Name == null) return;

            var parent = control.Parent;
            IUilView parentView = null;
            IUilViewPart parentViewPart;
            while (parent != null && ((parentView = parent as IUilView) == null ||
                (parentViewPart = parent as IUilViewPart) == null || parentViewPart.Name == null))
            {
                parent = parent.Parent;
            }

            if (parentView == null) return;

            var parentParts = parentView.Parts;
            if (parentParts == null)
                parentView.Parts = parentParts = new List<IUilViewPart>();

            parentParts.Add(part);
        }
    }
    

    public class UilViewPartContainer : global::Ext.Net.Container, IUilViewPart
    {
        public UilController Controller { get; set; }
        public string ViewID { get; set; }
        string IUilViewPart.Name { get { return ViewID; } }
        public IList<IUilViewPart> Parts { get; set; }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            UilViewPartHelper.RegisterAsPart(this);
        }

        public void AdaptToController() { }
    }


    public class UilViewPartPanel : global::Ext.Net.Panel, IUilViewPart
    {
        public UilController Controller { get; set; }
        public string ViewID { get; set; }
        string IUilViewPart.Name { get { return ViewID; } }
        public IList<IUilViewPart> Parts { get; set; }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            UilViewPartHelper.RegisterAsPart(this);
        }

        public void AdaptToController() { }
    }

}
